﻿// owner 蒋家伟

#pragma once
// qt
#include <QObject>
#include <QVariant>

// jsdk
#include "ThreadDeleter.h"
#include "ISerialPort.h"
#include "SerialPortHardwareWorker.h"

class QThread;
namespace jsdk
{
    class ISerialPortEventHandler;
    class IHardwareEventHandler;
    class TaskId;

    class SerialPortHardwareCompoent : public QObject
    {
        Q_OBJECT
    public:
        virtual ~SerialPortHardwareCompoent() {}

        /// \ brief 创建一个硬件组件
        /// \ in pHardwareEventHandler 硬件事件处理者
        /// \ in pSocketHandler 套接字事件处理者
        static OwnerPtr<SerialPortHardwareCompoent> create(IHardwareEventHandler* pHardwareEventHandler = nullptr, ISerialPortEventHandler* pSerialPortEventHandler = nullptr);

        /// \ brief IDevice Start的接口内部需要调用此函数去启动硬件组件
        /// \ return true 表明启动成功
        bool start(
            const std::string& portName,
            int baudRate,
            short dataBits,
            short stopBits,
            short parity,
            short flowControl
            );

        /// \ brief 设备重新连接
        /// \ return true 表明重连成功
        bool reConnect(
            const std::string& portName,
            int baudRate,
            short dataBits,
            short stopBits,
            short parity,
            short flowControl
            ) const;

        /// \ brief 当前硬件设备停止工作
        void stop();

        /// \ brief 向当前硬件组件加入一个任务
        void addTask(const TaskId& taskId) const;

        /// \ brief 发送一个消息
        void sendMessage(std::string&& msg, int64_t length) const;

        /// \ brief 是否在线
        bool isOnline() const;

    private:
        SerialPortHardwareCompoent() {}
        bool init() const;

#pragma region 与HardwareWorker跨线程的信号
    signals:
        void addTasks(QVariant vTaskId) const;

#pragma region 与HardwareWorker跨线程的信号

    private:
        OwnerPtr<ISerialPort> m_opSerialPort;
        OwnerPtr<SerialPortHardwareWorker> m_opSerialPortHardwareWorker;
        OwnerPtr<QThread, ThreadDeleter> m_opThread;
    };
}